package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/sign")
public class SignServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户信息
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码不能为空");
            return;
        }
        UserDao userDao=new UserDao();
        User user=userDao.selectByName(username);
        if(user==null) {
            //用户不存在
            resp.getWriter().write(username+" "+password);
            User user1=new User();
            user1.setUsername(username);
            user1.setPassword(password);
            resp.getWriter().write(objectMapper.writeValueAsString(user1));
            userDao.insert(user1);
           // resp.sendRedirect("blog-login.html");
        }else{
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名重复");
            return;
    }

    }
}
